//
//  BaiDuLocationViewController.m
//  MIT-AffordSuperMarket
//
//  Created by apple on 15/11/21.
//  Copyright © 2015年 河南大实惠电子商务有限公司. All rights reserved.
//

#import "BaiDuLocationViewController.h"
//vendor
#import "ManagerGlobeUntil.h"
#import "UIColor+Hex.h"
#import "Global.h"
#import "UIImage+ColorToImage.h"
#import "MBProgressHUD.h"
#import "ManagerHttpBase.h"
//untils
#import "NSString+Conversion.h"
//baidu
#import <BaiduMapAPI_Base/BMKBaseComponent.h>
//view
#import "BaiDuLocationCell.h"
//model
#import "XiaoQuAndStoreInfoModel.h"
//controller
#import "StoreListController.h"
typedef NS_ENUM(NSInteger, ErrorViewType) {
    knetworkError = 0,//联网失败
    kdingweiError = 1,//定位失败
    kcloudSearchError //云检索失败
};
@interface BaiDuLocationViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    BOOL _isYunJianSuoSuccess;
    UIButton *_errorButton;
    UIImageView *_errorImageView;
    UILabel *_errorMessageLabel;
    UILabel *_errorSubMessageLabel;
    ErrorViewType _errorType;
}

@property (nonatomic, weak) BMKMapView *mapView;
@property (nonatomic, strong)UIView *errorview;
@property (nonatomic, strong)UIView *successview;
@property (nonatomic, strong) NSString *str;

@property (nonatomic,retain) UILabel *nowcity;

@property (nonatomic,retain) UILabel *area;
@property (nonatomic,retain) UILabel *areaAddress;


@property (nonatomic,retain) UITableView *tableView;
@property (nonatomic,strong) UIImageView *leftLine;
@property (nonatomic,strong) NSMutableArray *poiArray;

@end

@implementation BaiDuLocationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"定位";
    [self addBackNavItem];
     _poiArray=[NSMutableArray array];
    self.view.backgroundColor = [UIColor colorWithHexString:@"#efefef"];
    //适配ios7
    if( ([[[UIDevice currentDevice] systemVersion] doubleValue]>=7.0))
    {
        self.navigationController.navigationBar.translucent = NO;
    }
    if ([ManagerGlobeUntil sharedManager].isNetworkReachability) {
        [self settingBaiDuKey];
    }
    
    //初始化子视图
    [self settingSubView];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    
    if ([ManagerGlobeUntil sharedManager].isNetworkReachability) {
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        _locService.delegate = self;
    } else {
         [self showErrorViewWithErrorType:knetworkError];
         [self.view insertSubview:self.errorview aboveSubview:self.successview];
    }
    if (_errorType == kdingweiError) {//从定位列表返回情况
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }
    
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    _locService.delegate = nil;
    _search.delegate = nil;
}
#pragma mark -- 百度地图参数设置
//设置百度key
- (void)settingBaiDuKey {
    
    [self settingMapViewParamer];
    [self settingLocationService];
}
//设置百度视图
- (void)settingMapViewParamer {
    [self.mapView setZoomLevel:14.0];
     _mapView.userTrackingMode = BMKUserTrackingModeNone;//设置定位的状态
}
//初始化BMKLocationService
- (void)settingLocationService {
    //初始化BMKLocationService
    _locService = [[BMKLocationService alloc]init];
    [_locService startUserLocationService];
}
#pragma mark -- 停止定位

-(void)StopLocating
{
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    [_locService stopUserLocationService];
}
#pragma mark -- BMKLocationServiceDelegate（百度定位）
/**
 *在地图View将要启动定位时，会调用此函数
 *@param mapView 地图View
 */
- (void)willStartLocatingUser
{
    NSLog(@"start locate");
}

/**
 *用户方向更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    //[_mapView updateLocationData:userLocation];
    NSLog(@"heading is %@",userLocation.heading);
    
}

/**
 *用户位置更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    
    //位置信息
    
    CLLocation *location =userLocation.location;
    // 拿到定位的经纬度
    NSString *x1 = [NSString stringWithFormat:@"%f", location.coordinate.longitude];
    NSString *y1 = [NSString stringWithFormat:@"%f", location.coordinate.latitude];
    NSString *z1 =@",";
    NSString  *string = [x1 stringByAppendingString:z1];
    _str = [string stringByAppendingString:y1];
    if (_str.length != 0) {
        [_locService setDelegate:nil];
        //启动云检索
        [self StartCloudSearch];
    }

}
/**
 *在地图View停止定位后，会调用此函数
 *@param mapView 地图View
 */
- (void)didStopLocatingUser {
   
}

/**
 *定位失败后，会调用此函数
 *@param mapView 地图View
 *@param error 错误号，参考CLError.h中定义的错误号
 */
- (void)didFailToLocateUserWithError:(NSError *)error{
     [MBProgressHUD hideHUDForView:self.view animated:YES];
    [self.view insertSubview:self.errorview aboveSubview:self.successview];
    [self showErrorViewWithErrorType:kdingweiError];
}
#pragma mark -- BMKCloudSearchDelegate（百度云检索）
//获取检索信息
-(void)onGetCloudPoiResult:(NSArray*)poiResultList searchType:(int)type errorCode:(int)error
{
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    if (error == BMKErrorOk) {
        
        [self.view insertSubview:self.successview aboveSubview:self.errorview];
        BMKCloudPOIList* result = [poiResultList firstObject];
        [self.poiArray removeAllObjects];
        
        isDescending = NO;
        [self.poiArray addObjectsFromArray:[result.POIs sortedArrayUsingFunction:sortedArrayWithDistance context:NULL]];
        if ([self.poiArray count] != 0) {//判断云检索是否返回数据
            _isYunJianSuoSuccess = YES;
            [self refreshDataSouce];
        } else {//未检索到小区
           [self showErrorViewWithErrorType:kcloudSearchError];
        }
        
    } else {
        [self showErrorViewWithErrorType:kcloudSearchError];
        [self.view insertSubview:self.errorview aboveSubview:self.successview];
        
    }
    
    
}
//获取云检索数据进行刷新table
- (void)refreshDataSouce {
    BMKCloudPOIInfo *poiInfo = (BMKCloudPOIInfo*)[self.poiArray firstObject];
    _nowcity.text=poiInfo.city;
    NSString *uID = [NSString stringISNull:[NSString stringWithFormat:@"%d",poiInfo.uid]];
    [_tableView reloadData];
    [self LoadXiaoQuInfoDataWithBaiDuUID:uID selected:NO xiaoQuName:poiInfo.title xiaoQuAddress:poiInfo.address shopName:[poiInfo.customDict objectForKey:@"shopName"]];
}



#pragma mark -- 开启周围云检索
//dGscuztU0zE131kfsxerHBcy   124311
-(void)StartCloudSearch
{
    //初始化云检索服务
    _search = [[BMKCloudSearch alloc]init];
    _search.delegate = self;
    
    //初始化对象
    BMKCloudNearbySearchInfo *cloudNearbySearch = [[BMKCloudNearbySearchInfo alloc]init];
    cloudNearbySearch.ak = BaiDuDingWeiServerKey;
    cloudNearbySearch.geoTableId = BaiDuDingWeiTableID;
    cloudNearbySearch.pageIndex = 0;
    cloudNearbySearch.pageSize = 10;
    //用的时候 把定位经纬度传过来
    cloudNearbySearch.location =_str;
    
    cloudNearbySearch.radius = BaiDuDingWeiRadius;
    cloudNearbySearch.keyword = BaiDuDingWeiKeyword;
    BOOL flag = [_search nearbySearchWithSearchInfo:cloudNearbySearch];
    if(flag){
        NSLog(@"周边云检索发送成功");
    } else {
        NSLog(@"周边云检索发送失败");
        [self showErrorViewWithErrorType:kcloudSearchError];

    }
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    
}


#pragma mark -- requestData
- (void)LoadXiaoQuInfoDataWithBaiDuUID:(NSString*)uid selected:(BOOL)isSelected xiaoQuName:(NSString*)name xiaoQuAddress:(NSString*)address shopName:(NSString *)shopName{
    //保存小区UID
    //请求参数说明： SIGNATURE  设备识别码
    ManagerHttpBase *manager = [ManagerHttpBase sharedManager];
    NSMutableDictionary *parameter = [[NSMutableDictionary alloc]init];
    [parameter setObject:uid forKey:@"BAIDUKEY"];
    __weak typeof(self)weakSelf = self;
    [manager parameters:parameter customPOST:@"common/location" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dataDic = (NSDictionary*)responseObject;
            NSString *msg = [dataDic objectForKey:@"MSG"];
            NSString *state = [NSString stringTransformObject:[dataDic objectForKey:@"STATE"]];//状态码
            if ([state isEqualToString:@"0"]) {//请求成功
                if (dataDic.count != 0) {
                    XiaoQuAndStoreInfoModel *model = [[XiaoQuAndStoreInfoModel alloc]init];
                    model.xiaoQuID = [NSString stringTransformObject:[[[dataDic objectForKey:@"OBJECT"] objectForKey:@"COMMUNITY"] objectForKey:@"ID"]];
                    model.xiaoQuName = [NSString stringTransformObject:[[[dataDic objectForKey:@"OBJECT"] objectForKey:@"COMMUNITY"] objectForKey:@"TITLE"]];
                    model.xiaoQuAddress = [NSString stringTransformObject:[[[dataDic objectForKey:@"OBJECT"] objectForKey:@"COMMUNITY"] objectForKey:@"ADDRESS"]];
                    model.storeID = [NSString stringTransformObject:[[[dataDic objectForKey:@"OBJECT"] objectForKey:@"STORE"] objectForKey:@"ID"]];
                    model.storeName = [NSString stringTransformObject:[[[dataDic objectForKey:@"OBJECT"] objectForKey:@"STORE"] objectForKey:@"TITLE"]];
                    model.storeAddress = [NSString stringTransformObject:[[[dataDic objectForKey:@"OBJECT"] objectForKey:@"STORE"] objectForKey:@"ADDRESS"]];
                    model.storePhone = [NSString stringTransformObject:[[[dataDic objectForKey:@"OBJECT"] objectForKey:@"STORE"] objectForKey:@"TEL"]];
                    NSString *storeStartTime = [NSString stringTransformObject:[[[dataDic objectForKey:@"OBJECT"] objectForKey:@"STORE"] objectForKey:@"BEGINTIME"]];
                    NSString *storeEndTime = [NSString stringTransformObject:[[[dataDic objectForKey:@"OBJECT"] objectForKey:@"STORE"] objectForKey:@"ENDTIME"]];
                    model.storeYingYeTime = [NSString stringWithFormat:@"%@-%@",storeStartTime,storeEndTime];
                    model.storePeiSongIntroduce = [NSString stringTransformObject:[[[dataDic objectForKey:@"OBJECT"] objectForKey:@"STORE"] objectForKey:@"DELIVERYDES"]];
                    [[ManagerGlobeUntil sharedManager] updataXiaoquAndStoreInfoWithModel:model];
                    [[NSNotificationCenter defaultCenter] postNotificationName:PRODUCTCOUNTCHANGE object:nil];
                    
                    if (isSelected ) {
                        if (_errorType != knetworkError) {
                            
                        }
                        if (weakSelf.suppperControllerType == kIntroduction_ControllerSupperController) {
                            [[NSNotificationCenter defaultCenter] postNotificationName:DINGWEISUCCESS object:nil];
                            //
                        } else {
                            [weakSelf dismissViewControllerAnimated:YES completion:nil];
                        }
                        
                    }
                    _area.text=name;
                    _areaAddress.text=address;
                }
            }else {//请求失败
                [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:msg inView:weakSelf.view];
            }
        }
        
    } failure:^(bool isFailure) {
        [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:@"网络连接终中断,请重试~" inView:weakSelf.view];
        
    }];
}

#pragma mark -- UITableViewDataSource
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return HightScalar(72);
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;

{
    return self.poiArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    static NSString *identfy = @"chanpincanshu";
    BaiDuLocationCell *cell = [tableView dequeueReusableCellWithIdentifier:identfy];
    if (cell == nil) {
        cell = [[BaiDuLocationCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identfy];
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    BMKCloudPOIInfo *poiInfo = (BMKCloudPOIInfo*)[self.poiArray objectAtIndex:indexPath.row];
    [cell updateViewWithData:poiInfo];
    [cell.layer setBorderWidth:0.5];
    [cell.layer setBorderColor:[UIColor colorWithHexString:@"#dddddd"].CGColor];
    return cell;
}
#pragma mark -- UITableViewDelegate

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    BMKCloudPOIInfo *poiInfo = (BMKCloudPOIInfo*)[self.poiArray objectAtIndex:indexPath.row];
    
    _tableView.hidden=YES;
    NSString *uID = [NSString stringISNull:[NSString stringWithFormat:@"%d",poiInfo.uid]];
    
    [self LoadXiaoQuInfoDataWithBaiDuUID:uID selected:YES xiaoQuName:poiInfo.title xiaoQuAddress:poiInfo.address shopName:[poiInfo.customDict objectForKey:@"shopName"]];
    
    
}

#pragma mark -- 对云检索数据进行排序
bool isDescending; //是否降序
int rankType;//列的类型

NSInteger sortedArrayWithDistance(id obj1, id obj2, void *context) {
    if ([obj1 isKindOfClass:[BMKCloudPOIInfo class]]&&[obj2 isKindOfClass:[BMKCloudPOIInfo class]])
    {
        BMKCloudPOIInfo *data1 = (BMKCloudPOIInfo*)obj1;
        BMKCloudPOIInfo *data2 = (BMKCloudPOIInfo*)obj2;
        float v1 = 0,v2 = 0;
        //根据当前类型取值
        if (rankType != -1)
        {
            v1 = data1.distance;
            v2 = data2.distance;
        }
        
        if (v1 < v2)
        {
            return (isDescending ? NSOrderedDescending:NSOrderedAscending);
        }
        else if (v1 > v2)
        {
            return (isDescending ? NSOrderedAscending:NSOrderedDescending);
        }
        else
        {
            return NSOrderedSame;
        }
    }
    
    return NSOrderedSame;
}


#pragma mark -- buttonAction
//展示或隐藏云检索小区列表
-(void)btnClick:(UIButton*)sender
{
    UIButton *button = (UIButton*)sender;
    button.selected = !button.selected;
    if (button.selected) {
        _tableView.hidden=NO;
    }else{
        _tableView.hidden=YES;
    }
}
// 立即体验小区
- (void)errprViewButtonClick
{
    if (_errorType == knetworkError) {
        if ([ManagerGlobeUntil sharedManager].isNetworkReachability) {//已连接到网络
            [self settingBaiDuKey];
            _locService.delegate = self;
        } else {//未连接到网络
            [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:@"您当前网络不可用，请检查网络设置后重试" inView:self.view];
        }
        
    } else if (_errorType == kdingweiError) {
        StoreListController *storeListVC = [[StoreListController alloc]init];
        UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:storeListVC];
        [self presentViewController:nav animated:YES completion:^{
            
        }];
    } else if (_errorType == kcloudSearchError ) {
        [self LoadXiaoQuInfoDataWithBaiDuUID:@"1491112789" selected:YES xiaoQuName:@"大实惠总部" xiaoQuAddress:@"河南省郑州市金水区广场北路" shopName:@"大实惠总部店"];
    }
   
}

- (void)backBtnAction:(id)sender {
    if (self.suppperControllerType == kIntroduction_ControllerSupperController) {//从引导页进入
        if (_isYunJianSuoSuccess) {//有数据
            [[NSNotificationCenter defaultCenter] postNotificationName:DINGWEISUCCESS object:nil];
        } else {//无数据就退出应用
            
            if (IsIOS8) {
                [[NSUserDefaults standardUserDefaults] removeObjectForKey:Phone_Signature];
                exit(0);
            }
        }
    } else {//从其他页面
         [self dismissViewControllerAnimated:YES completion:nil];
    }
   
}
#pragma mark -- 展示网络连接失败或定位失败视图
- (void)showErrorViewWithErrorType:(ErrorViewType)errorType {
    NSString *buttonTitle = @"";
    NSString *errorMsg = @"";
    NSString *subErrorMsg = @"";
    NSString *imageName = @"";
    _errorType = errorType;
    if (errorType == knetworkError) {
        buttonTitle = @"立即重试";
        errorMsg = @"您当前网络不可用，请检查网络设置后重试";
        imageName = @"icon_nonetwork";
    } else if (errorType == kdingweiError) {
        buttonTitle = @"手动选择地址";
        subErrorMsg = @"无法获取您的定位~";
        errorMsg = @"请进入设置改为允许大实惠访问您的位置\n或者手动选择地址";
        imageName = @"icon_noarea";
    } else if (errorType == kcloudSearchError) {
        buttonTitle = @"继续浏览";
        errorMsg = @"当前位置暂不可配送，是否仍继续浏览";
        imageName = @"icon_noarea";
    }
    if (subErrorMsg.length == 0) {
        _errorSubMessageLabel.hidden = YES;
    } else {
        _errorSubMessageLabel.hidden = NO;
    }
    [_errorButton setTitle:buttonTitle forState:UIControlStateNormal];
    _errorSubMessageLabel.text = subErrorMsg;
    _errorImageView.image = [UIImage imageNamed:imageName];
    _errorMessageLabel.text = errorMsg;
}
#pragma mark -- 初始化视图
- (void)settingSubView {
    //第一分区
    UIView *oneSectionHeaderView = [self setViewWithFrame:CGRectMake(0, 13, VIEW_WIDTH, HightScalar(49)) backgroundColorName:@"#ffffff"];
    [self.view addSubview:oneSectionHeaderView];
    UIImageView *oneSectionImageView = [self setImageViewWithFrame:CGRectMake(HightScalar(18), HightScalar(49)/2 - HightScalar(23)/2, HightScalar(23), HightScalar(23))
                                                         imageName:@"icon_nowaddress"];
    [oneSectionHeaderView addSubview:oneSectionImageView];
    UILabel *oneSectionTitleView = [self setLabeWithFrame:CGRectMake(CGRectGetMaxX(oneSectionImageView.frame) + HightScalar(18)
                                                                     , 0
                                                                     , VIEW_WIDTH-100
                                                                     ,CGRectGetHeight(oneSectionHeaderView.bounds))
                                                     text:@"当前城市"
                                                     font:[UIFont systemFontOfSize:FontSize(16)] textColorName:@"#555555"];
    [oneSectionHeaderView.layer setBorderWidth:0.7];
    [oneSectionHeaderView.layer setBorderColor:[UIColor colorWithHexString:@"#dddddd"].CGColor];
    [oneSectionHeaderView addSubview:oneSectionTitleView];
    
    //第一分区内容
    _nowcity = [self setLabeWithFrame:CGRectMake(CGRectGetMinX(oneSectionImageView.frame)
                                                 ,  CGRectGetMaxY(oneSectionHeaderView.frame)
                                                 ,VIEW_WIDTH - 2*CGRectGetMinX(oneSectionImageView.frame)
                                                 , HightScalar(53))
                                 text:@""
                                 font:[UIFont systemFontOfSize:FontSize(16)] textColorName:@"#555555"];
    [self.view addSubview:_nowcity];
    //第二分区
    UIView *twoSectionHeaderView = [self setViewWithFrame:CGRectMake(CGRectGetMinX(oneSectionHeaderView.frame)
                                                                     , CGRectGetMaxY(self.nowcity.frame)
                                                                     , CGRectGetWidth(oneSectionHeaderView.bounds)
                                                                     , CGRectGetHeight(oneSectionHeaderView.bounds))
                                      backgroundColorName:@"#ffffff"];
    [self.view addSubview:twoSectionHeaderView];
    UIImageView *twoSectionImageView = [self setImageViewWithFrame:oneSectionImageView.frame imageName:@"icon_nowarea"];
    [twoSectionHeaderView addSubview:twoSectionImageView];
    UILabel *twoSectionTitleView = [self setLabeWithFrame:oneSectionTitleView.frame
                                                     text:@"所选便利店"
                                                     font:[UIFont systemFontOfSize:FontSize(16)] textColorName:@"#555555"];
    [twoSectionHeaderView.layer setBorderWidth:0.7];
    [twoSectionHeaderView.layer setBorderColor:[UIColor colorWithHexString:@"#dddddd"].CGColor];
    [twoSectionHeaderView addSubview:twoSectionTitleView];
    //第二分区内容
    UIView *twoSectionContentView = [self setViewWithFrame:CGRectMake(0, CGRectGetMaxY(twoSectionHeaderView.frame)
                                                                      , CGRectGetWidth(self.view.bounds), HightScalar(72))
                                       backgroundColorName:@"#efefef"];
    [self.view addSubview:twoSectionContentView];
    
    _area = [self setLabeWithFrame:CGRectMake(CGRectGetMinX(twoSectionImageView.frame)
                                              , HightScalar(14)
                                              , VIEW_WIDTH
                                              , HightScalar(26)) text:@""
                              font:[UIFont systemFontOfSize:FontSize(16)]
                     textColorName:@"#555555"];
    _area.contentMode = UIViewContentModeBottom;
    [twoSectionContentView addSubview:_area];
    _areaAddress = [self setLabeWithFrame:CGRectMake(CGRectGetMinX(_area.frame)
                                                     , CGRectGetMaxY(_area.frame)
                                                     , CGRectGetWidth(_area.bounds)
                                                     , HightScalar(25))
                                     text:@""
                                     font:[UIFont systemFontOfSize:FontSize(13)]
                            textColorName:@"#999999"];
    _areaAddress.contentMode = UIViewContentModeTop;
    [twoSectionContentView addSubview:_areaAddress];
    
    //错误提醒视图
    CGRect errorViewFrame = CGRectMake(0
                                       , CGRectGetMaxY(twoSectionContentView.frame)
                                       , CGRectGetWidth(self.view.bounds)
                                       , CGRectGetHeight(self.view.bounds) - CGRectGetMaxY(twoSectionContentView.frame));
    _errorview = [self setViewWithFrame:errorViewFrame backgroundColorName:@"#efefef"];
    _errorImageView = [self setImageViewWithFrame:CGRectMake((VIEW_WIDTH-HightScalar(120))/2, 0, HightScalar(120), HightScalar(120)) imageName:@"icon_noarea"];
    [_errorview addSubview:_errorImageView];
   
    _errorSubMessageLabel = [self setLabeWithFrame:CGRectMake(15, CGRectGetMaxY(_errorImageView.frame)+10, VIEW_WIDTH-30, HightScalar(20))
                                              text:@""
                                              font:[UIFont systemFontOfSize:FontSize(15)] textColorName:@"#555555"];
    _errorSubMessageLabel.textAlignment = NSTextAlignmentCenter;
    [_errorview addSubview:_errorSubMessageLabel];
    
    _errorMessageLabel = [self setLabeWithFrame:CGRectMake(CGRectGetMinX(_errorSubMessageLabel.frame)
                                                           , CGRectGetMaxY(_errorSubMessageLabel.frame)
                                                           , CGRectGetWidth(_errorSubMessageLabel.bounds)
                                                           , CGRectGetHeight(_errorSubMessageLabel.bounds) + HightScalar(18))
                                                   text:@""
                                                   font:[UIFont systemFontOfSize:FontSize(15)] textColorName:@"#999999"];
    _errorMessageLabel.textAlignment = NSTextAlignmentCenter;
    _errorMessageLabel.numberOfLines = 0;
    _errorMessageLabel.lineBreakMode = NSLineBreakByCharWrapping;
    [_errorview addSubview:_errorMessageLabel];
    // 立即进入体验小区
    _errorButton = [self setButtonWithFrame:CGRectMake(VIEW_WIDTH/3, CGRectGetMaxY(_errorMessageLabel.frame)+HightScalar(15), VIEW_WIDTH/3, HightScalar(40))
                                               title:@"继续浏览" titleColorName:@"#e63f17" titleFont:[UIFont systemFontOfSize:FontSize(15)]];
    
    UIImage *errprViewButtonImage = [UIImage createImageWithColor:[UIColor whiteColor]
                                                            frame:CGRectMake(0, 0, CGRectGetWidth(_errorButton.bounds)
                                                                             , CGRectGetHeight(_errorButton.bounds))];
    [_errorButton setBackgroundImage:errprViewButtonImage forState:UIControlStateNormal];
    [_errorButton.layer setBorderWidth:0.5];
    [_errorButton.layer setBorderColor:[UIColor colorWithHexString:@"#e63f17"].CGColor];
    [_errorButton addTarget:self action:@selector(errprViewButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [_errorButton.layer setMasksToBounds:YES];
    [_errorButton.layer setCornerRadius:4.0];
    [self.errorview addSubview:_errorButton];
    
    //正常内容视图
    CGRect successViewFrame = CGRectMake(0
                                         , CGRectGetMinY(self.errorview.frame)
                                         , CGRectGetWidth(self.view.bounds)
                                         , CGRectGetHeight(self.view.bounds) - CGRectGetMaxY(twoSectionContentView.frame));
    _successview = [self setViewWithFrame:successViewFrame backgroundColorName:@"#ffffff"];
    UIButton *selectedStoreBtn = [self setButtonWithFrame:CGRectMake(0, 0, self.view.frame.size.width, HightScalar(49))
                                                    title:@"切换便利店" titleColorName:@"#555555" titleFont:[UIFont systemFontOfSize:FontSize(16)]];
    
    
    selectedStoreBtn.selected = NO;
    UIImage *appointmentsImage = [UIImage createImageWithColor:[UIColor whiteColor]
                                                         frame:CGRectMake(0, 0, CGRectGetWidth(selectedStoreBtn.bounds), CGRectGetHeight(selectedStoreBtn.bounds))];
    [selectedStoreBtn setBackgroundImage:appointmentsImage forState:UIControlStateNormal];
    [selectedStoreBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    selectedStoreBtn.titleLabel.textAlignment=NSTextAlignmentCenter;
    [selectedStoreBtn.layer setBorderWidth:0.7];
    [selectedStoreBtn.layer setBorderColor:[UIColor colorWithHexString:@"#dddddd"].CGColor];
    [_successview addSubview:selectedStoreBtn];
    _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0
                                                            , CGRectGetMaxY(selectedStoreBtn.frame)
                                                            , CGRectGetWidth(self.errorview.bounds)
                                                            ,VIEW_HEIGHT- CGRectGetMaxY(selectedStoreBtn.frame)-64-CGRectGetMinY(_successview.frame))
                                           style:UITableViewStylePlain];
    
    _tableView.delegate=self;
    _tableView.dataSource=self;
    _tableView.hidden=YES;
    [_successview addSubview:_tableView];
    
}


- (UIView*)setViewWithFrame:(CGRect)frame backgroundColorName:(NSString*)colorName {
    UIView *view = [[UIView alloc]initWithFrame:frame];
    view.backgroundColor = [UIColor colorWithHexString:colorName];
    return view;
}
- (UIImageView*)setImageViewWithFrame:(CGRect)frame imageName:(NSString*)imageName {
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:frame];
    imageView.image = [UIImage imageNamed:imageName];
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    imageView.backgroundColor = [UIColor clearColor];
    return imageView;
}
- (UILabel*)setLabeWithFrame:(CGRect)frame text:(NSString*)text font:(UIFont*)font textColorName:(NSString*)colorName {
    UILabel *label = [[UILabel alloc]initWithFrame:frame];
    label.text = text;
    label.font = font;
    label.textColor = [UIColor colorWithHexString:colorName];
    label.backgroundColor = [UIColor clearColor];
    return label;
}
- (UIButton *)setButtonWithFrame:(CGRect)frame title:(NSString*)title titleColorName:(NSString*)titleColorName titleFont:(UIFont*)font {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = frame;
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:[UIColor colorWithHexString:titleColorName] forState:UIControlStateNormal];
    button.titleLabel.font = font;
    return button;
}
- (void)dealloc {
    if (_mapView) {
        _mapView = nil;
    }
}

@end
